#! /bin/bash

HOST=$(ip add | grep inet | awk {'print $2'} | sed -n '3p' |awk -F "/" {'print $1'})
echo ${HOST} | awk '{match($0,"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])",a)}{print a[0]}' > gateway_pre
GATEWAY_PRE=$(cat gateway_pre)
rm -rf gateway_pre

IP_SUF=$1
if [ ! -n "${IP_SUF}" ]; then
	EXAMPLE_IP=101
    echo "please input init ip! like ${EXAMPLE_IP}"
    echo "for example: ./initIpAddr.sh ${EXAMPLE_IP}"
    echo "will init your ip addr: ${GATEWAY_PRE}.${EXAMPLE_IP}"
    exit
fi

IPADDR=${GATEWAY_PRE}.${IP_SUF}
NETMASK=255.255.255.0
GATEWAY=${GATEWAY_PRE}.2
DNS1=114.114.114.114

ENS33=/etc/sysconfig/network-scripts/ifcfg-ens33
mv ${ENS33} ${ENS33}.bak

cat > ${ENS33}  <<EOF
TYPE="Ethernet"
PROXY_METHOD="none"
BROWSER_ONLY="no"
BOOTPROTO="static"
DEFROUTE="yes"
IPV4_FAILURE_FATAL="no"
IPV6INIT="yes"
IPV6_AUTOCONF="yes"
IPV6_DEFROUTE="yes"
IPV6_FAILURE_FATAL="no"
IPV6_ADDR_GEN_MODE="stable-privacy"
NAME="ens33"
UUID="94fc26c7-d2dd-49d6-97e9-cba7496f5d02"
DEVICE="ens33"
ONBOOT="yes"
EOF
echo IPADDR=${IPADDR}    >> ${ENS33}
echo NETMASK=${NETMASK}  >> ${ENS33}
echo GATEWAY=${GATEWAY}  >> ${ENS33}
echo DNS1=${DNS1}        >> ${ENS33}

systemctl restart network
 
echo "ipaddr init successed: ${IPADDR}"
